# -*- coding: utf-8 -*-

from flask import Flask
from werkzeug.utils import import_string

from mongoengine import connect

from config import config

from utils.logger import set_root_logger
from utils.auth import Auth
from utils.redis import RedisInterface


auth = Auth()
redis_interface = RedisInterface()

def create_app(config_name='dev'):
    app =  Flask(__name__)

    if config_name is None:
        config_name = 'dev'

    app.config.from_object(config[config_name])
    app.config.setdefault('MONGODB_URI', 'mongodb://127.0.0.1:27017')
    app.config.setdefault('GRAPH_PAGE_LENGTH', 20)

    for bp in app.config.get('INSTALLED_BLUEPRINTS', []):
        bp = import_string(bp)
        app.register_blueprint(bp)

    set_root_logger()

    connect(
        app.config.get('MONGODB_DB'),
        host=app.config['MONGODB_URI']
    )

    auth.init_app(app)
    redis_interface.init_app(app)

    return app
